package com.jdbc.text6;


/*创建数据库基类*/

import java.sql.*;

public class BaseDao {
    Connection connection = null;
    ResultSet resultSet=null;
    PreparedStatement preparedStatement=null;
    ResultSet rs=null;
    //获取数据库连接
    public boolean getConnection(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            String url ="jdbc:mysql://127.0.0.1:3306/kgcnews";
            String user="root";
            String pass="123456";
            connection  = DriverManager.getConnection(url,user,pass);

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /*增删改*/
    public int executeUpdate(String sql,Object[] params){
        int updateRows = 0;
        if (this.getConnection()){
            try{
                preparedStatement = connection.prepareStatement(sql);
                for (int i=0;i<params.length;i++){
                    preparedStatement.setObject(i+1,params[i]);
                }
                updateRows= preparedStatement.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return updateRows;
    }
    //查
    public  ResultSet executeSQL(String sql,Object[] params){
        if (this.getConnection()){
            try {
                preparedStatement= connection.prepareStatement(sql);
                for (int i=0;i<params.length;i++){
                    preparedStatement.setObject(i+1,params[i]);
                }
                rs = preparedStatement.executeQuery();

            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        return rs;
    }

}
